package com.example.usermanager.controller;

import com.example.usermanager.mapper.UserMapper;
import com.example.usermanager.model.UserInfo;
import com.example.usermanager.tools.AppFinal;
import com.example.usermanager.tools.ResponseBody;
import com.example.usermanager.tools.SessionUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserMapper userMapper;
    @RequestMapping("/login")
    public ResponseBody<UserInfo> login(@RequestParam String username, @RequestParam String password, HttpServletRequest httpServletRequest){
        UserInfo login = userMapper.login(username, password);
        int status=-1;
        String message="用户名或密码错误";
        if (login!=null&&login.getId()>0){
            //登陆成功
            status=0;
            message="登陆成功";
            //存入session
            httpServletRequest.getSession().setAttribute(AppFinal.USERINFO_SESSION_KEY,login);
        }
        return new ResponseBody<>(status,message,login);
    }
    //欢迎
    @RequestMapping("/welcome")
    public ResponseBody<String> welcome(HttpServletRequest httpServletRequest){
        int status=-1;
        String message="请先登录";
        String data=null;
        if (SessionUtil.getUserBySession(httpServletRequest)!=null){
            status=0;
            message="";
            data="欢迎您,"+SessionUtil.getUserBySession(httpServletRequest).getUsername();
        }
        return new ResponseBody<>(status,message,data);
    }

    @RequestMapping("/goout")
    public ResponseBody<String> goout(HttpServletRequest httpServletRequest){
        int status=0;
        String message="注销成功";
        String data=null;
        if (SessionUtil.getUserBySession(httpServletRequest)!=null){
           httpServletRequest.getSession(false).removeAttribute(AppFinal.USERINFO_SESSION_KEY);
        }
        return new ResponseBody<>(status,message,data);
    }
    /**
     * 查询用户信息
     */
    @RequestMapping("/getlist")
    public Object getList(int cpage,
                          int psize,
                          String name,
                          String address,
                          String email,
                          HttpServletRequest request) {
        name = name.equals("") ? null : name;
        address = address.equals("") ? null : address;
        email = email.equals("") ? null : email;
        Integer isadmin = null;
        //是否登录
        // session 中获取是否为管理员
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(AppFinal.USERINFO_SESSION_KEY) != null) {
            UserInfo sessUser = (UserInfo) session.getAttribute(AppFinal.USERINFO_SESSION_KEY);
            if (sessUser.getIsadmin() == 0) {
                isadmin = 0;
            }
        }
        int sindex = (cpage - 1) * psize;
        // 查询的当月数据
        List<UserInfo> list = userMapper.getUserByPage(sindex, psize, name, address, email, isadmin);
        // 查询总条数
        int totalCount = userMapper.getUserCount(name, address, email, isadmin);
        // 分页总页数
        int tpage = (int) Math.ceil(totalCount / (psize * 1.0));
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("tpage", tpage);
        map.put("tcount", totalCount);
        map.put("status",0);
        return map;
    }

    /**
     * 删除用户信息
     */
    @RequestMapping("/del")
    public ResponseBody<Integer> del(String ids,HttpServletRequest httpServletRequest) {
        int status=-1;
        String message="删除失败";
        int data= -1;
        if (SessionUtil.getUserBySession(httpServletRequest)==null){
            message="请先登录";
            return  new ResponseBody<>(status,message,data);
        }
        if (ids != null && !ids.equals("")) {
            if (ids.contains(","))
                ids = ids.substring(0, ids.length() - 1);
            String[] idArr = ids.split(",");
            data = userMapper.del(idArr);
            status=0;
            message="";
        }
        return  new ResponseBody<>(status,message,data);
    }
    /**
     * 是否超管
     */
    @RequestMapping("/checkadmin")
    public ResponseBody<Integer>checkAdmin(HttpServletRequest httpServletRequest){
        int status=-1;
        String message="查不出该用户身份";
        int data=-1;
        UserInfo userInfo;
        HttpSession session = httpServletRequest.getSession(false);
        if (session!=null&&(userInfo= (UserInfo) session.getAttribute(AppFinal.USERINFO_SESSION_KEY))!=null){
            message="检查成功";
            status=0;
            data=userInfo.getIsadmin();
        }
        return new ResponseBody<>(status,message,data);
    }
    /**
     * 添加操作
     */
    @RequestMapping("/add")
    public ResponseBody<Integer>add(UserInfo userInfo,HttpServletRequest httpServletRequest){
        int status=-1;
        String message="添加用户失败";
        int data=-1;
        UserInfo userInfo1= SessionUtil.getUserBySession(httpServletRequest);
        if (userInfo1==null)
            message="请先登录";
        else{
           if (userInfo1.getIsadmin()==0&&userInfo.getIsadmin()==1){
               message="添加用户权限不足，请申请超级管理员";
           }
           else{
               if((data=userMapper.add(userInfo))>0){
                   status=0;
                   message="添加用户成功";
               }
           }
        }

        return new ResponseBody<>(status,message,data);
    }
    /**
     * 根据 id 查询文章
     */
    @RequestMapping("/getuser")
    public ResponseBody<UserInfo> getUser(@RequestParam int uid,HttpServletRequest httpServletRequest){
        int status=-1;
        String message="没有该用户，获取失败";

        if (SessionUtil.getUserBySession(httpServletRequest)==null){
            message="请先登录";
            return new ResponseBody<>(status,message,null);
        }
        UserInfo data=userMapper.getUserById(uid);
         if (data!=null){
            //验证权限
            if (data.getIsadmin()==1&&SessionUtil.getUserBySession(httpServletRequest).getIsadmin()==0){
                message="权限不足，无法修改";
                data=null;
            }
            else{
            status=0;
            message="";}
        }
        return new ResponseBody<>(status,message,data);
    }

    /**
     * 修改操作
     */
    @RequestMapping("update")
    public ResponseBody<Integer>update(UserInfo userInfo){
        int status=-1;
        String message="修改失败,请重新再试";
        int data=-1;
        if ((data= userMapper.update(userInfo))>0){
            status=0;
            message="";
        }
        return new ResponseBody<>(status,message,data);
    }
}
